package com.thinkgem.jeesite.modules.book.service;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.book.dao.BookPurchaseDao;
import com.thinkgem.jeesite.modules.book.entity.*;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * 采购Controller
 *
 * @author zc
 * @version 2013-11-03
 */
@Service
@Transactional(readOnly = true)
public class BookPurchaseService extends CrudService<BookPurchaseDao, BkPurchaseBatch>{

    @Autowired
    private BookPurchaseDao bookPurchaseDao;
    @Autowired
    private BookMgrService bookMgrService;
    @Autowired
    private BookStoreService bookStoreService;

    @Transactional(readOnly = false)
    public void saveDetails(List<BkPurchaseBatchDetail> details){
        bookPurchaseDao.saveDetails(details);
    }

    @Transactional(readOnly = false)
    public int insert(BkPurchaseBatch batch){
        return bookPurchaseDao.insert(batch);
    }

    public Page<BkPurchaseBatchDetail> findDetails(Page<BkPurchaseBatchDetail> page, String batchId){
        BkPurchaseBatchDetail detail = new BkPurchaseBatchDetail();
        detail.setBatchId(Integer.parseInt(batchId));

        detail.setPage(page);
        page.setList(bookPurchaseDao.findPurchaseBatchDetail(detail));
        return page;
    }
    public BkPurchaseBatchDetail findPurchaseBatchDetailByBkId(String bkId){
        return bookPurchaseDao.findPurchaseBatchDetailByBkId(bkId);
    }

    @Transactional(readOnly = false)
    public void updateStatus(BkPurchaseBatch bkPurchaseBatch){
        bookPurchaseDao.updateStatus(bkPurchaseBatch);
    }
    @Transactional(readOnly = false)
    public void updateOtherWorkStatus(){
        bookPurchaseDao.updateOtherWorkStatus();
    }

    @Transactional(readOnly = false)
    public void savePrice(int batchId, double fixedPrice, double discountedPrice){
        bookPurchaseDao.savePrice(batchId, fixedPrice, discountedPrice);
    }

    @Transactional(readOnly = false)
    public int deleteBatch(BkPurchaseBatch bkPurchaseBatch){
        return bookPurchaseDao.deleteBatch(bkPurchaseBatch);
    }

    @Transactional(readOnly = false)
    public int deleteDetail(BkPurchaseBatch bkPurchaseBatch){
        return bookPurchaseDao.deleteDetail(bkPurchaseBatch);
    }

    @Transactional(readOnly = false)
    public int deleteDetailbyId(String pbdId){
        return bookPurchaseDao.deleteDetailbyId(pbdId);
    }

    @Transactional(readOnly = false)
    public int update(BkPurchaseBatch batch){
        return bookPurchaseDao.update(batch);
    }

    public BkPurchaseBatchDetail getBatchDetailById(int pbdId){
        return bookPurchaseDao.getBatchDetailById(pbdId);
    }
    public BkPurchaseBatch getCurrentWorkBatch(BkPurchaseBatch bkPurchaseBatch){ return bookPurchaseDao.getCurrentWorkBatch(bkPurchaseBatch);}
    @Transactional(readOnly = false)
    public void updateDetails(List<BkPurchaseBatchDetail> details){
        for(BkPurchaseBatchDetail detail : details){
            bookPurchaseDao.updateDetail(detail);
        }
    }


    @Transactional(readOnly = false)
    public synchronized Result savePurchase(String batchId, String batchDate, String remarks, String param){
        // 修改批次状态
        BkPurchaseBatch batch = this.get(batchId);
        batch.setRemarks(remarks);
        batch.setBatchDate(DateUtils.parseDate(batchDate));
        batch.setStatus(BkPurchaseBatch.STATUS_OK);
        int result = this.update(batch);
        if(result > 0){
            String[] params = param.split("&");
            // 计算码洋，实洋
            double fixedPrice = 0D;

            // 设置数据库中的编码初始值
            String maxBarCode = bookStoreService.getMaxBarCode();
            maxBarCode = (StringUtils.isNotEmpty(maxBarCode)) ? maxBarCode.substring(4) : "0";
            int barCodeLength = maxBarCode.length();
            int peMaxBarCode = Integer.parseInt(maxBarCode);

            List<BkPurchaseBatchDetail> details = new ArrayList<>();
            List<BkBookstore> bookstores = new ArrayList<>();

            for(int i = 3; i < params.length; i = i + 3){
                int pbdId = Integer.parseInt(getValue(params[i]));
                double discountedPrice = Double.parseDouble(getValue(params[i + 1]));
                int mxArrived = Integer.parseInt(getValue(params[i + 2]));

                BkPurchaseBatchDetail detail = this.getBatchDetailById(pbdId);
                detail.setDiscountedPrice(discountedPrice);
                detail.setMxArrived(mxArrived);
                details.add(detail);


                // 修改库存
                BkBookinfo bookinfo = bookMgrService.getByIsbn(detail.getBkIsbn());

                BkBookstore bookstore;
                for(int k= 0; k < mxArrived; k++){
                    bookstore = new BkBookstore();
                    bookstore.setBkId(bookinfo.getId());
                    bookstore.setIsbn(bookinfo.getIsbn());

                    IdGen.formatCount = peMaxBarCode;
                    bookstore.setBanid(IdGen.getMaxCode(barCodeLength));

                    bookstore.setTotalCount(1);
                    bookstore.setLeftCount(1);
                    bookstore.setUserId(UserUtils.getUser().getId());
                    bookstore.setBatch(batchId);
                    bookstore.setStatus(1);
                    bookstore.setIptTme(new Timestamp(System.currentTimeMillis()));
                    bookstores.add(bookstore);

                    peMaxBarCode++;
                }

            }
            bookStoreService.insertBookStores(bookstores);
            // 保存批次详情
            this.updateDetails(details);
            // 修改批次码洋，实洋
            /*bookPurchaseService.savePrice(Integer.parseInt(batchId), fixedPrice, 0D);*/
        }
        return new Result(Result.SUCCESS, "书籍登到成功！", batchId);

    }

    @Transactional(readOnly = false)
    public Result savePlan(String param){
        String[] params = param.split("&");

        BkPurchaseBatch batch = getBkPurchaseBatch(params);
        int result = this.insert(batch);

        if(result > 0){
            int batchId = batch.getBatchId();
            List<BkPurchaseBatchDetail> details = new ArrayList<>();
            BkPurchaseBatchDetail detail;
            for(int i = 3; i < params.length; i = i + 4){
                String isbn = getValue(params[i]);
                String bkId = getValue(params[i + 1]);
                double price = new Double(getValue(params[i + 2]));
                int mxCnt = Integer.parseInt(getValue(params[i + 3]));

                BkBookinfo bookinfo = bookMgrService.get(bkId);

                detail = new BkPurchaseBatchDetail(batchId, bkId, isbn, price,
                        0, mxCnt,
                        0, bookinfo.getBookname(),
                        bookinfo.getClasscode(),bookinfo.getOthername());
                details.add(detail);
            }
            this.saveDetails(details);
        }
        return new Result(Result.SUCCESS, "保存数据成功！", batch);
    }

    @Transactional(readOnly = false)
    public Result cancelPlan(String batchId){
        // 查询批次
        BkPurchaseBatch batch = this.get(batchId);

        // 修改批次状态为取消
        batch.setStatus(BkPurchaseBatch.STATUS_CANCEL);
        this.update(batch);

        bookStoreService.deleteStoreByBatchId(batchId);

        return new Result(Result.SUCCESS, "书籍取消登到成功！", batchId);
    }

    private BkPurchaseBatch getBkPurchaseBatch(String[] params){
        String batchNumber = getValue(params[0]);
        String planDate = getValue(params[1]).replaceAll("%3A", ":").replace("+", " ");
        String remarks = getValue(params[2]);
        return new BkPurchaseBatch(batchNumber, DateUtils.parseDate(planDate), remarks, BkPurchaseBatch.STATUS_PLAN);
    }

    private String getValue(String param){
        String[] params = param.split("=");
        if(params.length >= 2){
            return params[1];
        }
        else{
            return "";
        }
    }

    @Transactional(readOnly = false)
    public void savePrint(String startsn, String endsn, String school){
        dao.savePrint(startsn, endsn, school);
    }

    public BkBookBan getMaxPrintbanId(){
        return dao.getMaxPrintbanId();
    }

    public int checkRepeatBatchNumber(String batchNumber) {
        return dao.checkRepeatBatchNumber(batchNumber);
    }


    @Transactional(readOnly = false)
    public int saveStartBanId(String startsn, String loginName){
        return dao.saveStartBanId(startsn, loginName);
    }

    @Transactional(readOnly = false)
    public int updateStartBanId(String startsn, String loginName){
        return dao.updateStartBanId(startsn, loginName);
    }

    public boolean isSetUpStartBanId(String loginName){
        List<BkBookBan> list = dao.getPrintbanId(loginName);
        return list!= null && !list.isEmpty();
    }

    /**
     * 生成 索书号
     * @param bkId
     * @param classcode
     * @param isBooks
     * @param booksNum
     * @return
     */
    public String createPlace(String bkId, String classcode, boolean isBooks, String booksNum){
        BkBookinfo info= bookMgrService.get(bkId);
        // 相同的ISBN，不同的书籍类型，使用第一个store表中的classcode
        List<BkBookinfo> bookinfos = bookMgrService.getBookInfosByIsbn(info.getIsbn());
        if(bookinfos != null && bookinfos.size()>=2)
        {
            String bkIds = "";
            for(BkBookinfo bookinfo : bookinfos){
                bkIds += "," + bookinfo.getId();
            }
            if(bkIds.startsWith(",")){
                bkIds = bkIds.substring(1);
            }
            classcode = StringUtils.defaultIfEmpty(bookStoreService.getClasscodeByBkIdsStr(bkIds), info.getClasscode());
        }

        return classcode + "/" + bookStoreService.createPlace(bkId, classcode, isBooks, booksNum);
    }
}
